import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.WeekFields;
import java.util.*;
import java.io.*;
import java.nio.file.*;

public class CalendarApp extends Application {
    private Stage primaryStage;
    private BorderPane root;
    private VBox calendarView;
    private ToggleGroup viewToggleGroup;
    private RadioButton monthViewBtn;
    private RadioButton yearViewBtn;
    private RadioButton weekViewBtn;
    
    // 当前日期和视图状态
    private LocalDate currentDate = LocalDate.now();
    private String currentView = "MONTH"; // MONTH, YEAR, WEEK
    private Label currentDateLabel;
    private static String ROOT_DIR = "D:\\Program\\Tem_Doc\\0001.临时文件"; // 默认值
    private static final String CONFIG_FILE_PATH = "config.json";
    private Map<LocalDate, TextArea> dateTextAreas = new HashMap<>();

    @Override
    public void start(Stage primaryStage) {
        loadConfig(); // 在初始化其他组件之前加载配置
        this.primaryStage = primaryStage;
        this.root = new BorderPane();
        
        createTopBar();
        createCalendarView();
        
        Scene scene = new Scene(root, 800, 600);
        primaryStage.setTitle("日历");
        primaryStage.setScene(scene);
        primaryStage.show();
        
        // 添加窗口大小变化监听器
        primaryStage.widthProperty().addListener((obs, oldVal, newVal) -> {
            refreshCalendar();
        });
        
        primaryStage.heightProperty().addListener((obs, oldVal, newVal) -> {
            refreshCalendar();
        });
        
        // 添加窗口关闭监听器，确保在关闭时保存所有事件
        primaryStage.setOnCloseRequest(event -> {
            saveAllEvents();
        });
    }
    
    private void createTopBar() {
        // 创建顶部工具栏
        HBox topBar = new HBox(10);
        topBar.setPadding(new Insets(10));
        topBar.setAlignment(Pos.CENTER_LEFT);
        
        // 视图切换按钮
        viewToggleGroup = new ToggleGroup();
        
        monthViewBtn = new RadioButton("月视图");
        monthViewBtn.setToggleGroup(viewToggleGroup);
        monthViewBtn.setSelected(true);
        
        yearViewBtn = new RadioButton("年视图");
        yearViewBtn.setToggleGroup(viewToggleGroup);
        
        weekViewBtn = new RadioButton("周视图");
        weekViewBtn.setToggleGroup(viewToggleGroup);
        
        // 添加事件监听器
        monthViewBtn.setOnAction(e -> switchToView("MONTH"));
        yearViewBtn.setOnAction(e -> switchToView("YEAR"));
        weekViewBtn.setOnAction(e -> switchToView("WEEK"));
        
        // 日期导航按钮
        Button prevButton = new Button("<");
        Button nextButton = new Button(">");
        Button todayButton = new Button("今天");
        
        currentDateLabel = new Label(currentDate.format(DateTimeFormatter.ofPattern("yyyy年MM月")));
        
        prevButton.setOnAction(e -> navigate(-1));
        nextButton.setOnAction(e -> navigate(1));
        todayButton.setOnAction(e -> {
            currentDate = LocalDate.now();
            refreshCalendar();
        });
        
        topBar.getChildren().addAll(
            monthViewBtn, yearViewBtn, weekViewBtn,
            new Separator(),
            prevButton, currentDateLabel, nextButton,
            new Separator(),
            todayButton
        );
        
        root.setTop(topBar);
    }
    
    private void createCalendarView() {
        calendarView = new VBox(10); // 恢复间距为10
        calendarView.setPadding(new Insets(10)); // 恢复边框留白为10
        calendarView.setAlignment(Pos.TOP_CENTER);
        
        // 使日历视图填充可用空间
        VBox.setVgrow(calendarView, Priority.ALWAYS);
        
        renderCalendar();
        
        root.setCenter(calendarView);
    }
    
    private void switchToView(String view) {
        currentView = view;
        refreshCalendar();
        
        // 更新导航栏中的视图切换按钮选中状态
        switch (view) {
            case "MONTH":
                monthViewBtn.setSelected(true);
                break;
            case "YEAR":
                yearViewBtn.setSelected(true);
                break;
            case "WEEK":
                weekViewBtn.setSelected(true);
                break;
        }
    }
    
    private void navigate(int direction) {
        switch (currentView) {
            case "MONTH":
                currentDate = currentDate.plusMonths(direction);
                break;
            case "YEAR":
                currentDate = currentDate.plusYears(direction);
                break;
            case "WEEK":
                currentDate = currentDate.plusWeeks(direction);
                break;
        }
        refreshCalendar();
    }
    
    private void refreshCalendar() {
        // 保存当前所有事件
        saveAllEvents();
        
        // 清空TextArea映射
        dateTextAreas.clear();
        
        // 更新导航栏中的日期标签
        updateCurrentDateLabel();
        
        calendarView.getChildren().clear();
        renderCalendar();
    }
    
    private void renderCalendar() {
        switch (currentView) {
            case "MONTH":
                renderMonthView();
                break;
            case "YEAR":
                renderYearView();
                break;
            case "WEEK":
                renderWeekView();
                break;
        }
    }
    
    private void updateCurrentDateLabel() {
        switch (currentView) {
            case "MONTH":
                currentDateLabel.setText(currentDate.format(DateTimeFormatter.ofPattern("yyyy年MM月")));
                break;
            case "YEAR":
                currentDateLabel.setText(currentDate.getYear() + "年");
                break;
            case "WEEK":
                LocalDate startOfWeek = currentDate.with(java.time.temporal.TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
                LocalDate endOfWeek = currentDate.with(java.time.temporal.TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
                currentDateLabel.setText(startOfWeek.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")) + " - " + 
                                       endOfWeek.format(DateTimeFormatter.ofPattern("MM月dd日")));
                break;
        }
    }
    
    private void renderMonthView() {
        // 显示月份和年份标题
        Label titleLabel = new Label(currentDate.format(DateTimeFormatter.ofPattern("yyyy年MM月")));
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
        
        // 创建星期标题行
        HBox weekdaysHeader = new HBox();
        weekdaysHeader.setSpacing(5); // 恢复间距为5
        weekdaysHeader.setPadding(new Insets(5, 0, 5, 0)); // 恢复上下边距
        HBox.setHgrow(weekdaysHeader, Priority.ALWAYS);
        
        String[] weekdays = {"一", "二", "三", "四", "五", "六", "日"};
        for (String day : weekdays) {
            Label dayLabel = new Label(day);
            dayLabel.setAlignment(Pos.CENTER);
            dayLabel.setStyle("-fx-font-weight: bold;");
            dayLabel.setMaxWidth(Double.MAX_VALUE);
            HBox.setHgrow(dayLabel, Priority.ALWAYS);
            weekdaysHeader.getChildren().add(dayLabel);
        }
        
        // 创建日期网格
        GridPane calendarGrid = new GridPane();
        calendarGrid.setHgap(2); // 恢复水平间距为2
        calendarGrid.setVgap(2); // 恢复垂直间距为2
        calendarGrid.setPadding(new Insets(5)); // 恢复网格边距
        calendarGrid.setPrefWidth(Region.USE_COMPUTED_SIZE);
        calendarGrid.setMaxWidth(Double.MAX_VALUE);
        calendarGrid.setMaxHeight(Double.MAX_VALUE);
        GridPane.setHgrow(calendarGrid, Priority.ALWAYS);
        GridPane.setVgrow(calendarGrid, Priority.ALWAYS);
        
        // 为网格添加列约束，使列能够根据窗口大小调整
        for (int i = 0; i < 7; i++) {
            ColumnConstraints columnConstraints = new ColumnConstraints();
            columnConstraints.setHgrow(Priority.ALWAYS);
            calendarGrid.getColumnConstraints().add(columnConstraints);
        }
        
        // 获取该月的第一天是星期几
        LocalDate firstDayOfMonth = currentDate.withDayOfMonth(1);
        DayOfWeek firstDayOfWeek = firstDayOfMonth.getDayOfWeek();
        
        // 计算第一天在网格中的位置 (周一为第一天)
        int firstDayPosition = firstDayOfWeek.getValue() - 1; // Java中周一为1，周日为7
        if (firstDayPosition == 0) firstDayPosition = 7; // 调整为周日为最后一天
        
        // 获取该月的总天数
        int daysInMonth = currentDate.lengthOfMonth();
        
        // 填充日期网格
        int row = 0;
        int col = firstDayPosition - 1; // 减1是因为索引从0开始
        
        // 填充月初的空位
        for (int i = 0; i < firstDayPosition - 1; i++) {
            Label emptyLabel = new Label("");
            emptyLabel.setMaxWidth(Double.MAX_VALUE);
            calendarGrid.add(emptyLabel, i, row);
        }
        
        // 已在网格创建时添加列约束
        
        // 计算可能的行数并添加行约束
        int maxRows = (firstDayPosition - 1 + daysInMonth + 6) / 7; // 向上取整计算行数
        for (int i = 0; i < maxRows; i++) {
            RowConstraints rowConstraints = new RowConstraints();
            rowConstraints.setVgrow(Priority.ALWAYS);
            rowConstraints.setMinHeight(30); // 设置合理的最小行高
            calendarGrid.getRowConstraints().add(rowConstraints);
        }
        
        // 填充该月的所有日期
        for (int day = 1; day <= daysInMonth; day++) {
            Button dayButton = new Button(String.valueOf(day));
            dayButton.setMinWidth(20); // 恢复最小宽度
            dayButton.setMinHeight(20); // 恢复最小高度
            dayButton.setMaxWidth(Double.MAX_VALUE);
            dayButton.setMaxHeight(Double.MAX_VALUE);
            GridPane.setFillWidth(dayButton, true);
            GridPane.setFillHeight(dayButton, true);
            
            // 检查是否是今天
            LocalDate currentDay = LocalDate.of(currentDate.getYear(), currentDate.getMonth(), day);
            if (currentDay.equals(LocalDate.now())) {
                dayButton.setStyle("-fx-background-color: #0078d7; -fx-text-fill: white;");
            }
            
            final int selectedDay = day;
            dayButton.setOnAction(e -> {
                // 跳转到周视图，以选定日期所在的周显示
                currentDate = LocalDate.of(currentDate.getYear(), currentDate.getMonth(), selectedDay);
                switchToView("WEEK");
            });
            
            calendarGrid.add(dayButton, col, row);
            
            col++;
            if (col > 6) { // 到达周日，换行
                col = 0;
                row++;
            }
        }
        
        calendarView.getChildren().addAll(titleLabel, weekdaysHeader, calendarGrid);
        
        // 设置 VBox 子项的生长策略
        VBox.setVgrow(titleLabel, Priority.NEVER);
        VBox.setVgrow(weekdaysHeader, Priority.NEVER);
        VBox.setVgrow(calendarGrid, Priority.ALWAYS);
    }
    
    private void renderYearView() {
        // 显示年份标题
        Label titleLabel = new Label(currentDate.getYear() + "年");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");
        
        // 创建月份网格 (3x4)
        GridPane monthsGrid = new GridPane();
        monthsGrid.setHgap(5); // 恢复水平间距为5
        monthsGrid.setVgap(5); // 恢复垂直间距为5
        monthsGrid.setPadding(new Insets(10)); // 恢复网格边距为10
        monthsGrid.setPrefWidth(Region.USE_COMPUTED_SIZE);
        monthsGrid.setMaxWidth(Double.MAX_VALUE);
        monthsGrid.setMaxHeight(Double.MAX_VALUE);
        GridPane.setHgrow(monthsGrid, Priority.ALWAYS);
        GridPane.setVgrow(monthsGrid, Priority.ALWAYS);
        
        // 为月份网格添加行和列约束
        for (int i = 0; i < 4; i++) {  // 4列
            ColumnConstraints columnConstraints = new ColumnConstraints();
            columnConstraints.setHgrow(Priority.ALWAYS);
            monthsGrid.getColumnConstraints().add(columnConstraints);
        }
        
        for (int i = 0; i < 3; i++) {  // 3行
            RowConstraints rowConstraints = new RowConstraints();
            rowConstraints.setVgrow(Priority.ALWAYS);
            rowConstraints.setMinHeight(80); // 设置合理的最小行高
            monthsGrid.getRowConstraints().add(rowConstraints);
        }
        
        // 显示所有月份
        String[] months = {
            "一月", "二月", "三月", "四月",
            "五月", "六月", "七月", "八月",
            "九月", "十月", "十一月", "十二月"
        };
        
        for (int month = 1; month <= 12; month++) {
            int row = (month - 1) / 4;
            int col = (month - 1) % 4;
            
            VBox monthBox = new VBox(5); // 恢复间距为5
            monthBox.setAlignment(Pos.CENTER);
            monthBox.setMinWidth(10);
            monthBox.setMinHeight(10);
            monthBox.setStyle("-fx-border-color: #ccc; -fx-border-radius: 5px;");
            monthBox.setPadding(new Insets(5)); // 恢复月份框的内边距为5
            monthBox.setMaxWidth(Double.MAX_VALUE);
            monthBox.setMaxHeight(Double.MAX_VALUE);
            GridPane.setFillWidth(monthBox, true);
            GridPane.setFillHeight(monthBox, true);
            VBox.setVgrow(monthBox, Priority.ALWAYS);
            
            // 计算当前字体大小
            int fontSize = calculateFontSize();
            
            Label monthLabel = new Label(months[month-1]);
            monthLabel.setStyle("-fx-font-weight: bold; -fx-font-size: " + (fontSize + 2) + "px;");
            
            // 显示完整的月份日历（包含星期标题）
            VBox monthCalendar = new VBox(1); // 恢复间距为1
            
            // 星期标题行
            HBox weekdaysHeader = new HBox();
            weekdaysHeader.setSpacing(1); // 恢复间距为1
            weekdaysHeader.setPadding(new Insets(1, 0, 1, 0)); // 恢复上下边距
            String[] weekdays = {"一", "二", "三", "四", "五", "六", "日"};
            for (String weekday : weekdays) {
                Label weekdayLabel = new Label(weekday);
                weekdayLabel.setAlignment(Pos.CENTER);
                weekdayLabel.setStyle("-fx-font-weight: bold; -fx-font-size: " + fontSize + "px;");
                weekdayLabel.setMaxWidth(Double.MAX_VALUE);
                HBox.setHgrow(weekdayLabel, Priority.ALWAYS);
                weekdaysHeader.getChildren().add(weekdayLabel);
            }
            
            // 日期网格
            GridPane monthGrid = new GridPane();
            monthGrid.setHgap(1);
            monthGrid.setVgap(1);
            monthGrid.setMinWidth(80);
            monthGrid.setMinHeight(60);
            monthGrid.setPadding(new Insets(1)); // 恢复网格边距为1
            
            // 为月份网格添加列约束
            for (int i = 0; i < 7; i++) { // 7天
                ColumnConstraints columnConstraints = new ColumnConstraints();
                columnConstraints.setHgrow(Priority.ALWAYS);
                monthGrid.getColumnConstraints().add(columnConstraints);
            }
            
            // 获取该月的第一天
            YearMonth yearMonth = YearMonth.of(currentDate.getYear(), month);
            LocalDate firstOfMonth = yearMonth.atDay(1);
            
            // 计算第一天在网格中的位置 (周一为第一天)
            DayOfWeek firstDayOfWeek = firstOfMonth.getDayOfWeek();
            int firstDayPosition = firstDayOfWeek.getValue() - 1; // Java中周一为1，周日为7
            if (firstDayPosition == 0) firstDayPosition = 7; // 调整为周日为最后一天
            
            // 获取该月的总天数
            int daysInMonth = yearMonth.lengthOfMonth();
            
            // 填充日期网格
            int gridRow = 0;
            int gridCol = firstDayPosition - 1; // 减1是因为索引从0开始
            
            // 填充月初的空位
            for (int i = 0; i < firstDayPosition - 1; i++) {
                Label emptyLabel = new Label("");
                emptyLabel.setStyle("-fx-font-size: " + fontSize + "px;");
                monthGrid.add(emptyLabel, i, gridRow);
            }
            
            // 填充该月的所有日期
            for (int day = 1; day <= daysInMonth; day++) {
                Label dayLabel = new Label(String.valueOf(day));
                dayLabel.setAlignment(Pos.CENTER);
                dayLabel.setStyle("-fx-font-size: " + fontSize + "px;");
                dayLabel.setMaxWidth(Double.MAX_VALUE);
                dayLabel.setMinWidth(8); // 设置合理的最小宽度
                dayLabel.setMinHeight(8); // 设置合理的最小高度
                
                // 检查是否是今天
                LocalDate currentDay = LocalDate.of(currentDate.getYear(), month, day);
                if (currentDay.equals(LocalDate.now())) {
                    dayLabel.setStyle("-fx-font-size: " + fontSize + "px; -fx-background-color: #0078d7; -fx-text-fill: white;");
                }
                
                monthGrid.add(dayLabel, gridCol, gridRow);
                
                gridCol++;
                if (gridCol > 6) { // 到达周日，换行
                    gridCol = 0;
                    gridRow++;
                    
                    // 为新行添加行约束
                    RowConstraints rowConstraints = new RowConstraints();
                    rowConstraints.setVgrow(Priority.ALWAYS);
                    rowConstraints.setMinHeight(10); // 设置合理的最小行高
                    monthGrid.getRowConstraints().add(rowConstraints);
                }
            }
            
            monthCalendar.getChildren().addAll(weekdaysHeader, monthGrid);
            monthBox.getChildren().addAll(monthLabel, monthCalendar);
            
            final int selectedMonth = month;
            monthBox.setOnMouseClicked(e -> {
                currentDate = LocalDate.of(currentDate.getYear(), selectedMonth, 1);
                switchToView("MONTH");
            });
            
            monthsGrid.add(monthBox, col, row);
        }
        
        calendarView.getChildren().addAll(titleLabel, monthsGrid);
        
        // 设置 VBox 子项的生长策略
        VBox.setVgrow(titleLabel, Priority.NEVER);
        VBox.setVgrow(monthsGrid, Priority.ALWAYS);
    }
    
    private void renderWeekView() {
        // 计算当前周的开始和结束日期 (周一到周日)
        LocalDate startOfWeek = currentDate.with(java.time.temporal.TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = currentDate.with(java.time.temporal.TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        
        // 计算当前字体大小
        int fontSize = calculateFontSize();
        
        // 显示周范围标题
        WeekFields weekFields = WeekFields.of(DayOfWeek.MONDAY, 1);
        int weekNumber = currentDate.get(weekFields.weekOfWeekBasedYear());
        Label titleLabel = new Label("第" + weekNumber + "周 (" +
                                   startOfWeek.format(DateTimeFormatter.ofPattern("MM月dd日")) + " - " +
                                   endOfWeek.format(DateTimeFormatter.ofPattern("MM月dd日")) + ")");
        titleLabel.setStyle("-fx-font-size: " + (fontSize + 6) + "px; -fx-font-weight: bold;");

        // 创建每日视图
        VBox weekBox = new VBox(5); // 恢复间距为5
        weekBox.setPadding(new Insets(5)); // 恢复外边距为5
        VBox.setVgrow(weekBox, Priority.ALWAYS);
        
        for (int i = 0; i < 7; i++) {
            LocalDate day = startOfWeek.plusDays(i);
            
            HBox dayBox = new HBox(10); // 恢复间距为10
            dayBox.setPadding(new Insets(5)); // 恢复内边距为5
            dayBox.setStyle("-fx-border-color: #ddd; -fx-border-width: 0 0 1 0;");
            dayBox.setMaxWidth(Double.MAX_VALUE);
            dayBox.setMaxHeight(Double.MAX_VALUE);
            HBox.setHgrow(dayBox, Priority.ALWAYS);
            VBox.setVgrow(dayBox, Priority.ALWAYS);
            
            // 显示星期和日期
            VBox dateInfo = new VBox(2); // 恢复间距为2
            dateInfo.setMinWidth(60); // 恢复最小宽度
            dateInfo.setPrefWidth(80); // 恢复首选宽度
            dateInfo.setMaxWidth(120); // 恢复最大宽度
            dateInfo.setMaxHeight(Double.MAX_VALUE);

            VBox.setVgrow(dateInfo, Priority.NEVER); // 不允许垂直生长
            HBox.setHgrow(dateInfo, Priority.NEVER); // 不允许水平生长
            
            Label dayOfWeekLabel = new Label(getDayOfWeekChinese(day.getDayOfWeek()));
            Label dateLabel = new Label(day.format(DateTimeFormatter.ofPattern("MM/dd")));
            
            // 增大字体大小
            dayOfWeekLabel.setStyle("-fx-font-weight: bold; -fx-font-size: " + (fontSize + 2) + "px;");
            dateLabel.setStyle("-fx-font-weight: bold; -fx-font-size: " + (fontSize + 4) + "px;");
            
            // 如果是今天，高亮显示
            if (day.equals(LocalDate.now())) {
                dateInfo.setStyle("-fx-background-color: #0078d7;");
                dayOfWeekLabel.setStyle("-fx-text-fill: white; -fx-font-size: " + (fontSize + 2) + "px;");
                dateLabel.setStyle("-fx-text-fill: white; -fx-font-weight: bold; -fx-font-size: " + (fontSize + 4) + "px;");
            }
            
            dateInfo.getChildren().addAll(dayOfWeekLabel, dateLabel);
            dateInfo.setAlignment(Pos.CENTER);
            
            // 显示事件区域
            VBox eventsBox = new VBox(2); // 恢复间距为2
            eventsBox.setMinHeight(50); // 恢复最小高度
            eventsBox.setMaxWidth(Double.MAX_VALUE);
            eventsBox.setMaxHeight(Double.MAX_VALUE);
            VBox.setVgrow(eventsBox, Priority.ALWAYS);
            HBox.setHgrow(eventsBox, Priority.ALWAYS);
            
            // 创建文本区域用于输入和显示事件
            TextArea eventTextArea = new TextArea();
            eventTextArea.setPrefHeight(80); // 恢复首选高度
            eventTextArea.setMaxHeight(Double.MAX_VALUE);
            eventTextArea.setWrapText(true);
            VBox.setVgrow(eventTextArea, Priority.ALWAYS);
            
            // 保存TextArea引用以便后续操作
            dateTextAreas.put(day, eventTextArea);
            
            // 加载已存在的事件内容
            loadEventsForDate(day, eventTextArea);
            
            eventsBox.getChildren().add(eventTextArea);
            
            dayBox.getChildren().addAll(dateInfo, eventsBox);
            
            final LocalDate selectedDay = day;
            dayBox.setOnMouseClicked(e -> {
                showAlert("选中日期", "您选择了 " + selectedDay.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日")));
            });
            
            weekBox.getChildren().add(dayBox);
        }
        
        calendarView.getChildren().addAll(titleLabel, weekBox);
        
        // 设置 VBox 子项的生长策略
        VBox.setVgrow(titleLabel, Priority.NEVER);
        VBox.setVgrow(weekBox, Priority.ALWAYS);
    }
    
    private String getDayOfWeekChinese(DayOfWeek dayOfWeek) {
        switch (dayOfWeek) {
            case MONDAY: return "周一";
            case TUESDAY: return "周二";
            case WEDNESDAY: return "周三";
            case THURSDAY: return "周四";
            case FRIDAY: return "周五";
            case SATURDAY: return "周六";
            case SUNDAY: return "周日";
            default: return "";
        }
    }
    
    /**
     * 根据窗口大小计算合适的字体大小
     * @return 字体大小
     */
    private int calculateFontSize() {
        // 获取当前窗口大小
        double width = primaryStage.getWidth();
        double height = primaryStage.getHeight();
        
        // 根据窗口大小计算字体大小
        // 基础字体大小为10，根据窗口大小进行缩放
        double baseSize = 10;
        double scale = Math.min(width / 800.0, height / 600.0); // 基于800x600的基准窗口
        
        return Math.max(8, (int) (baseSize * scale)); // 最小字体为8
    }
    
    private void showAlert(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }
    
    /**
     * 加载指定日期的事件内容
     * @param date 日期
     * @param textArea 文本区域
     */
    private void loadEventsForDate(LocalDate date, TextArea textArea) {
        try {
            String filePath = getEventFilePath(date);
            Path path = Paths.get(filePath);
            if (Files.exists(path)) {
                String content = new String(Files.readAllBytes(path));
                textArea.setText(content);
            }
        } catch (IOException e) {
            // 文件读取失败，不显示错误，保持文本区域为空
        }
    }
    
    /**
     * 获取事件文件路径
     * @param date 日期
     * @return 文件路径
     */
    private String getEventFilePath(LocalDate date) {
        String year = String.valueOf(date.getYear());
        String month = String.format("%02d", date.getMonthValue());
        String day = String.format("%02d", date.getDayOfMonth());
        String dayOfWeek = getDayOfWeekChinese(date.getDayOfWeek());
        
        String dirPath = ROOT_DIR + File.separator + year + File.separator + year + "-" + month;
        String fileName = year + "-" + month + "-" + day + "_" + dayOfWeek + ".md";
        
        // 确保目录存在
        try {
            Files.createDirectories(Paths.get(dirPath));
        } catch (IOException e) {
            // 目录创建失败，继续执行
        }
        
        return dirPath + File.separator + fileName;
    }
    
    /**
     * 保存指定日期的事件内容
     * @param date 日期
     */
    private void saveEventsForDate(LocalDate date) {
        TextArea textArea = dateTextAreas.get(date);
        if (textArea != null) {
            try {
                String content = textArea.getText();
                // 如果内容为空，则不保存文件
                if (content != null && !content.trim().isEmpty()) {
                    String filePath = getEventFilePath(date);
                    Path path = Paths.get(filePath);
                    Files.write(path, content.getBytes());
                } else if (content != null && content.trim().isEmpty()) {
                    // 如果内容为空，且文件已存在，则删除文件
                    String filePath = getEventFilePath(date);
                    Path path = Paths.get(filePath);
                    if (Files.exists(path)) {
                        Files.delete(path);
                    }
                }
            } catch (IOException e) {
                showAlert("保存失败", "无法保存事件到文件: " + e.getMessage());
            }
        }
    }
    
    /**
     * 保存所有日期的事件内容
     */
    private void saveAllEvents() {
        for (LocalDate date : dateTextAreas.keySet()) {
            saveEventsForDate(date);
        }
    }
    
    /**
     * 从JSON配置文件加载配置
     */
    private void loadConfig() {
        try {
            Path configPath = Paths.get(CONFIG_FILE_PATH);
            if (Files.exists(configPath)) {
                String content = new String(Files.readAllBytes(configPath));
                // 简单解析JSON配置文件
                ROOT_DIR = parseJsonString(content, "rootDir");
            }
        } catch (Exception e) {
            System.err.println("读取配置文件失败: " + e.getMessage());
            // 使用默认值
        }
    }
    
    /**
     * 简单解析JSON字符串中的指定字段
     * @param json JSON字符串
     * @param fieldName 字段名
     * @return 字段值
     */
    private String parseJsonString(String json, String fieldName) {
        try {
            // 查找 "fieldName" : "value" 模式
            String pattern = "\"" + fieldName + "\"\\s*:\\s*\"([^\"]*)\"";
            java.util.regex.Pattern p = java.util.regex.Pattern.compile(pattern);
            java.util.regex.Matcher m = p.matcher(json);
            if (m.find()) {
                return m.group(1).replace("\\\\", "\\"); // 处理转义字符
            }
        } catch (Exception e) {
            System.err.println("解析JSON字段失败: " + e.getMessage());
        }
        return ROOT_DIR; // 返回默认值
    }
    
    /**
     * 显示日期详情视图
     * @param date 选定的日期
     */
    private void showDateDetailView(LocalDate date) {
        // 创建新的视图容器
        BorderPane dateDetailView = new BorderPane();
        dateDetailView.setPadding(new Insets(10));
        
        // 创建顶部工具栏
        HBox topBar = new HBox(10);
        topBar.setAlignment(Pos.CENTER_LEFT);
        
        // 返回按钮
        Button backButton = new Button("返回");
        backButton.setOnAction(e -> refreshCalendar()); // 返回月视图
        
        // 日期标题
        Label dateLabel = new Label(date.format(DateTimeFormatter.ofPattern("yyyy年MM月dd日 EEEE")));
        dateLabel.setStyle("-fx-font-size: 20px; -fx-font-weight: bold;");
        
        topBar.getChildren().addAll(backButton, dateLabel);
        
        dateDetailView.setTop(topBar);
        
        // 创建事件编辑区域
        TextArea eventTextArea = new TextArea();
        eventTextArea.setPromptText("在此输入事件...");
        eventTextArea.setWrapText(true);
        
        // 设置文本区域填充可用空间
        VBox.setVgrow(eventTextArea, Priority.ALWAYS);
        VBox eventBox = new VBox(10, new Label("事件:"), eventTextArea);
        eventBox.setPadding(new Insets(10, 0, 0, 0));
        VBox.setVgrow(eventBox, Priority.ALWAYS);
        
        // 加载已存在的事件内容
        loadEventsForDate(date, eventTextArea);
        
        // 保存按钮
        Button saveButton = new Button("保存");
        saveButton.setOnAction(e -> {
            try {
                String content = eventTextArea.getText();
                // 保存内容到文件
                String filePath = getEventFilePath(date);
                Path path = Paths.get(filePath);
                
                if (content != null && !content.trim().isEmpty()) {
                    // 如果内容不为空，保存文件
                    Files.write(path, content.getBytes());
                    showAlert("保存成功", "事件已保存到 " + filePath);
                } else if (content != null && content.trim().isEmpty()) {
                    // 如果内容为空，且文件已存在，则删除文件
                    if (Files.exists(path)) {
                        Files.delete(path);
                    }
                    showAlert("保存成功", "已清除该日期的事件");
                }
            } catch (IOException ex) {
                showAlert("保存失败", "无法保存事件到文件: " + ex.getMessage());
            }
        });
        
        // 底部按钮栏
        HBox bottomBar = new HBox(10);
        bottomBar.setAlignment(Pos.CENTER_RIGHT);
        bottomBar.getChildren().add(saveButton);
        
        // 组装视图
        VBox centerBox = new VBox(10, eventBox, bottomBar);
        centerBox.setPadding(new Insets(10));
        VBox.setVgrow(centerBox, Priority.ALWAYS);
        
        dateDetailView.setCenter(centerBox);
        
        // 替换主视图为日期详情视图
        root.setCenter(dateDetailView);
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}